<template>
  <div :style="styleObj">
    <div v-if="hackReset" class="txtScroll-top">
      <!--表头-->
      <div class="title">
        <div
          v-for="(item, index) in header"
          :style="[headerTableStlye,tableFiledWidth(index),tableRowHeight()]"
          :key="index"
        >
          {{ item.name }}
        </div>
      </div>
      <!--数据-->
      <div class="bd">
        <ul class="infoList" :style="infoListStyle">
          <li v-for="(item, index) in getShowList()" :key="index" :style="tableRowHeight()" >
            <div
              v-for="(itemChild, idx) in header"
              :key="idx"
              :style="[bodyTableStyle, bodyTable(index),tableFiledWidth(idx),tableRowHeight()]"
            >
              <MarqueeText :value="value" :content="item[itemChild.key]"/>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import vue from "vue";
import VueSuperSlide from "vue-superslide";
import MarqueeText from "@/components/MarqueeText";
import Animation from "@/utils/animation"
vue.use(VueSuperSlide);
export default {
  props: {
    value: Object,
    ispreview: Boolean
  },
  components:{
    MarqueeText
  },
  data() {
    return {
      hackReset: true,
      rollConfig: {   // 滚动配置
        isRoll :false, //是否滚动
        effect :'top', //  { code: 'top', name: '上滚动' }, { code: 'topLoop', name: '上循环滚动' },
        interTime:2500,
        delayTime:500,
        scroll:1,
        vis:'5',
        rowHeight:50
      },
      header: [],
      list: [],
      showList:[],
      optionsSetUp: {},
      optionsPosition: {},
      optionsData: {},
      currentScrollY:0 , //当前滚动的位置
      scrollInterval:null,
    };
  },
  computed: {
    infoListStyle(){
        const rollSet = this.optionsSetUp;
        let vis = rollSet.vis; //可见行数
        let rowHeight = rollSet.rowHeight;//行高
      return {
        "position":"relative",
        "height":`${vis * rowHeight}px`,
        "padding":"0px",
        "margin":"0px",
        "top":`${this.currentScrollY}px`,
        "width":`100%`
      }
    },
    styleObj() {
      const allStyle = this.optionsPosition;
      return {
        position: this.ispreview ? "absolute" : "static",
        width: allStyle.width + "px",
        height: allStyle.height + "px",
        left: allStyle.left + "px",
        top: allStyle.top + "px",
        background: this.optionsSetUp.tableBgColor,
        overflow: 'hidden'
        
      };
    },
    headerTableStlye() {
      const headStyle = this.optionsSetUp;
      return {
        "text-align": headStyle.textAlign,
        "font-size": headStyle.fontSize + "px",
        "border-style": headStyle.isLine ? "solid" : "none",
        "border-width": headStyle.borderWidth + "px",
        "border-color": headStyle.borderColor,
        display: headStyle.isHeader ? "block" : "none",
        color: headStyle.headColor,
        "background-color": headStyle.headBackColor
      };
    },
    bodyTableStyle() {
      const bodyStyle = this.optionsSetUp;
      return {
        "text-align": bodyStyle.textAlign,
        "font-size": bodyStyle.fontSize + "px",
        "border-style": bodyStyle.isLine ? "solid" : "none",
        "border-width": bodyStyle.borderWidth + "px",
        "border-color": bodyStyle.borderColor,
        color: bodyStyle.bodyColor,
        "background-color": bodyStyle.tableBgColor
      };
    }
  },
  watch: {
    value: {
      handler(val) {
        this.optionsSetUp = val.setup;
        this.optionsPosition = val.position;
        this.optionsData = val.data;
        this.initData();
      },
      deep: true
    }
  },
  mounted() {
    this.optionsSetUp = this.value.setup;
    this.optionsPosition = this.value.position;
    this.optionsData = this.value.data;
    this.initData();
  
  },
  methods: {
     getShowList(){
       //debugger;
      let showList = [];
      //计算需要补充的list
      let vis = this.rollConfig.vis; //可见行数
      showList.push(...this.list)

      if(this.rollConfig.effect == 'topLoop'){
          if(this.list.length > vis){
              //补充展示数量的item
              showList.push(...this.list.slice(0,vis))
          }  
      }          
      return showList;
    },
    
    initData() {
      this.setOptionsRoll();
      this.handlerHead();
      this.handlerData();
      this.setFieldListener();
    },
    //设置滚动属性
    setOptionsRoll(){
      const rollConfig  = this.rollConfig;
      const rollSet = this.optionsSetUp;
      rollConfig.isRoll = rollSet.isRoll; //是否滚动
      rollConfig.effect = rollSet.effect; //  { code: 'top', name: '上滚动' }, { code: 'topLoop', name: '上循环滚动' },
      rollConfig.interTime = rollSet.interTime;//滚动间隔
      rollConfig.delayTime = rollSet.delayTime;//动画效果时间
      rollConfig.scroll = rollSet.scroll;//滚动数量
      rollConfig.vis = rollSet.vis; //可见行数
      rollConfig.rowHeight = rollSet.rowHeight;//行高
      this.rollConfig = rollConfig;
      this.startScroll();
    },
    /**
     * 开始滚动
     */
    startScroll(){
      this.currentScrollY = 0;
      if(this.scrollInterval){
        clearInterval(this.scrollInterval)
      }
      if(this.rollConfig.isRoll && this.rollConfig.vis  < this.list.length){
        this.scrollInterval = setTimeout(this.scrollHandler,this.rollConfig.interTime)
      }
    },    
    scrollHandler(){
      let _this = this;
      //获取配置参数
      let effect = this.rollConfig.effect; //  { code: 'top', name: '上滚动' }, { code: 'topLoop', name: '上循环滚动' },
      let delayTime = this.rollConfig.delayTime;//动画效果时间
      let scroll = this.rollConfig.scroll;//滚动数量
      let vis = this.rollConfig.vis; //可见行数
      let rowHeight = this.rollConfig.rowHeight;//行高
      let visHeight = vis * rowHeight;//可视高度
      let scrollDistance = rowHeight * scroll; //单次滚动距离

      let totalHeight = (this.list.length) * rowHeight;//可滚动的总高度  
      //初始化计算参数
      let startY = this.currentScrollY;//起始值
      if(effect == 'top'){
        let isRollback = startY + totalHeight <= visHeight;
        //console.log(`回滚到第一行 totalHeight == currentScrollY: ${startY + totalHeight} <= ${visHeight}` )
        if(isRollback){//回滚到第一行            
          //向上滚动
          scrollDistance = this.currentScrollY;  
          Animation.animation(scrollDistance,0,delayTime,'Linear',(value,isEnd)=>{  
            _this.currentScrollY = value;           
            _this.infoListStyle.top = _this.currentScrollY  + 'px';
            if(isEnd){ //结束后 回滚到初始状态 在重新进行滚动
              //console.log(`回滚到第一行 totalHeight == currentScrollY: ${totalHeight} == ${_this.currentScrollY}` )
              //结束
              if(_this.scrollInterval){
                  clearInterval(_this.scrollInterval)
                }   
              _this.scrollInterval = setTimeout(_this.scrollHandler,_this.rollConfig.interTime)               
            }
          })

        }else{
          //向下滚动
          Animation.animation(0,scrollDistance,delayTime,'Linear',(value,isEnd)=>{  
            _this.currentScrollY = startY - value;
            _this.infoListStyle.top = _this.currentScrollY  + 'px';
            if(isEnd){ //结束后 回滚到初始状态 在重新进行滚动
              //console.log(`totalHeight == currentScrollY: ${totalHeight} == ${_this.currentScrollY}` )
              //结束
              if(_this.scrollInterval){
                  clearInterval(_this.scrollInterval)
                }   
              _this.scrollInterval = setTimeout(_this.scrollHandler,_this.rollConfig.interTime)               
            }
          })
        }

    }else{
       
        if(0 == this.currentScrollY + totalHeight){//等于总高度时 置0
          startY = 0;
        }
        let endY = startY - scrollDistance; //目标值

        let residualHeight  = totalHeight + endY;//如果为负值，表示滑动超出  需要减去对应部分距离
        if(residualHeight < 0) {
            scrollDistance = scrollDistance + residualHeight;
        }
    
        //获取总高度
        Animation.animation(0,scrollDistance,delayTime,'Linear',(value,isEnd)=>{
          _this.currentScrollY = startY - value;
          _this.infoListStyle.top = _this.currentScrollY  + 'px';
          if(isEnd){
            //console.log(`totalHeight == currentScrollY: ${totalHeight} == ${_this.currentScrollY}` )
            //结束
            if(_this.scrollInterval){
                clearInterval(_this.scrollInterval)
              }   
            _this.scrollInterval = setTimeout(_this.scrollHandler,_this.rollConfig.interTime)               
          }
        })
    }
    },
    setFieldListener(){
      if(!this.ispreview){
          return ;
       }
      const _this = this;
      const optionsSetup = this.optionsSetUp;
      const fieldName = optionsSetup.fieldName;  
      if (!this.$bus._events[fieldName]) {       
          this.$bus.on(fieldName,(data) => {  
            _this.currentScrollY = 0;      
            _this.handlerStaticData(data);
            //_this.hackResetFun();
          });
      }
    },
    handlerHead() {
      const head = this.optionsSetUp.dynamicAddTable;
      this.header = head;
    },
    handlerData() {
      const tableData = this.optionsData;
      tableData.dataType == "staticData"
        ? this.handlerStaticData(tableData.staticData)
        : this.handlerDynamicData(tableData.dynamicData, tableData.refreshTime);
    },
    handlerStaticData(data) {
      this.list = data;
      this.startScroll();
    },
    handlerDynamicData(data, refreshTime) {
      if (!data) return;
      if (this.ispreview) {
        this.getEchartData(data);
        this.flagInter = setInterval(() => {
          this.getEchartData(data);
        }, refreshTime);
      } else {
        this.getEchartData(data);
      }
    },
    getEchartData(val) {
      const data = this.queryEchartsData(val);
      data.then(res => {
        this.list = res;
       this.startScroll();
      });
    },
    // 计算 奇偶背景色
    bodyTable(index) {
      var styleJson = {};
      if (index % 2) {
        styleJson["background-color"] = this.optionsSetUp.eventColor
      } else {
        styleJson["background-color"] = this.optionsSetUp.oldColor
      }
      return styleJson;
    },
    tableRowHeight(){
      var styleJson = {};
      if(this.optionsSetUp.rowHeight){
        styleJson['height'] = this.optionsSetUp.rowHeight+'px';
        styleJson['line-height'] = this.optionsSetUp.rowHeight+'px';
      }else{
        styleJson['height'] =this.options.rowHeight
        styleJson['line-height'] = this.optionsSetUp.rowHeight+'px';
      }
      return styleJson;
    },
    tableFiledWidth(index){
      var styleJson = {};
      if(this.optionsSetUp.dynamicAddTable[index].width ){
        styleJson["width"] = this.optionsSetUp.dynamicAddTable[index].width
      }
      return styleJson
    }
  }
};
</script>
<style lang="scss" scoped>
/* 本例子css */
.txtScroll-top {
  overflow: hidden;
  position: relative;
}

.title {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.title > div {
  height: 50px;
  line-height: 50px;
  width: 100%;
}

.txtScroll-top .bd {
  width: 100%;
  overflow: hidden;
}

.txtScroll-top .infoList li {
  height: 50px;
  line-height: 50px;
  display: flex;
  flex-direction: row;
}

.txtScroll-top .infoList li > div {
  width: 100%;
}

/*.txtScroll-top .infoList li:nth-child(n) {
  background: rgb(0, 59, 81);
}

.txtScroll-top .infoList li:nth-child(2n) {
  background: rgb(10, 39, 50);
}*/
</style>
